##=============================================================================
## Appendix: Figure 9
##=============================================================================

##-----------------
# clear environment
rm(list=ls())
options(stringsAsFactors = FALSE, scipen = 999)
# source("R/functions.R")

seed <- sample.int(.Machine$integer.max, 1)
set.seed(seed)

ipak <- function(pkg){new.pkg <- pkg[!(pkg %in% installed.packages()[, "Package"])]
if(length(new.pkg)) install.packages(new.pkg, dependencies = TRUE)
sapply(pkg, require, character.only = TRUE)
}

packages <- c("tidyverse", "Hmisc", "knitr")

ipak(packages)

##---------
# Load data
#setwd("/Users/austinknuppe/Library/CloudStorage/Dropbox/Ukraine2022WartimeSurvey/Paper_peace/final_version_oct_2024/replication-scripts")
load("clean_ukraine_data.RData")

## Create Correlation Heat Plot
cors <- function(df) { 
  M <- Hmisc::rcorr(as.matrix(df))
  Mdf <- map(M, ~data.frame(.x))
}

formatted_cors <- function(df){
  cors(df) %>%
    map(~rownames_to_column(.x, var = "measure1")) %>%
    map(~pivot_longer(.x, -measure1, names_to = "measure2")) %>% 
    bind_rows(.id = "id") %>%
    pivot_wider(names_from = id, values_from = value) %>%
    mutate(sig_p = ifelse(P < .05, T, F), p_if_sig = ifelse(P <.05, P, NA), r_if_sig = ifelse(P <.05, r, NA)) 
}

dat %>%
  dplyr::select(displaced, frontline_b, per_idx_invcov, fam_idx_invcov,
                viina_cum_adm2, save_lives, compromise_idx_terr_z,
                compromise_idx_full_z) %>% 
  rename(`Displaced` = displaced,
         `District-Level \n Combat Events` = viina_cum_adm2, 
         `Frontline Oblast` = frontline_b,
         `Personal \n Victimization` = per_idx_invcov,
         `Family \n Victimization` = fam_idx_invcov,
         `Save Lives` = save_lives,
         `Compromise Index \n (Full) ` = compromise_idx_full_z,
         `Compromise Index \n (Terr.) ` = compromise_idx_terr_z) %>% 
  formatted_cors() %>% 
  ggplot(aes(measure1, measure2, fill=r, label=round(r_if_sig,2))) +
  geom_tile() + 
  scale_fill_gradient2(mid="#FBFEF9",low="#0C6291",high="#A63446", 
                       limits=c(-1,1)) +
  labs(x = NULL, y = NULL, fill = "Pearson's\nCorrelation", 
       title = "Correlations in both waves", 
       subtitle = "Only significant Pearson's correlation coefficients shown") +
  geom_text() +
  theme_classic() +
  scale_x_discrete(expand=c(0,0)) + 
  scale_y_discrete(expand=c(0,0)) +
  theme(legend.position = "bottom",
        legend.direction = "horizontal",
        text = element_text(family = "Arial Narrow", size = 14))

rm(list = ls())
##=============================================================================
## End of File
##=============================================================================